<?php
/**
 * User: surestdeng
 * Date: 2020/4/11
 * Time: 20:22:21
 */

namespace App\Services\Video;


use App\Models\Video\UserModel;
use GuzzleHttp\Client;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class LoginService
{
    private $client;

    public function __construct()
    {
        $this->client = new Client();
    }

    /**
     * 微信登录
     * User: surest
     * Date: 2020/4/11
     * @param $code
     * @param $name
     * @param $avatar
     * @return array
     */
    public function wxLogin($code, $name, $avatar)
    {
        $xcx = config('wechat.xcx');
        $url = $xcx['url'];
        $url = sprintf($url, Arr::get($xcx, 'app_id'), Arr::get($xcx, 'secret_id'), $code);

        $data = $this->client->get($url);
        $data = $data->getBody()->getContents();
        $data = json_decode($data, true);
        $openId = Arr::get($data, 'openid');

        if(!$openId) {
            return [false, '获取用户唯一标示失败'];
        }
        $this->saveToGetUserInfo($name, $avatar, $openId);

        $token = $this->setLogin($openId);
        return [true, $token];
    }

    public function saveToGetUserInfo($name, $avatar, $open_id)
    {
        $data = compact('name', 'avatar', 'open_id');
        $user = UserModel::query()->where('open_id', $open_id)->first();
        if(!$user) {
            UserModel::query()->insert($data);
        }else{
            $id = $user->id;
            UserModel::query()->where('id', $id)->update($data);
        }

        return $data;
    }

    /**
     * 设置登录
     * User: surest
     * Date: 2020/4/11
     * @param $openId
     * @return string
     */
    public function setLogin($openId)
    {
        $token = md5($openId . time());
        $redis = getRedis();
        # 过期策略 https://learnku.com/laravel/t/31486
        $redis->set(Enum::LOGIN_KEY . $token, $openId, 'EX', Enum::LOGIN_KEY_EXPIRE);
        UserModel::query()->where('open_id', $openId)->update(['login_time' => date('Y-m-d H:i:s')]);
        return $token;
    }

    /**
     * 失效
     * User: surest
     * Date: 2020/4/11
     */
    public function setLogout($token)
    {
        $redis = getRedis();
        $redis->del([Enum::LOGIN_KEY]);
    }

    /**
     * 获取用户信息
     * User: surest
     * Date: 2020/4/11
     * @param $token
     */
    public function getUserInfo($token)
    {
        return getUserInfo(['id', 'name', 'avatar', 'source', 'count', 'integral', 'phone']);
    }
}
